package com.lier.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.lier.common.constant.AuthServerConstant;
import com.lier.common.utils.R;
import com.lier.common.valid.ExceptionTypeEnum;
import com.lier.common.vo.MemberRegisterVo;
import com.lier.common.vo.MemberResponseVo;
import com.lier.gulimall.auth.feign.MemberFeignService;
import com.lier.gulimall.auth.feign.ThirdPartFeignService;
import com.lier.gulimall.auth.vo.UserLoginVo;
import com.lier.gulimall.auth.vo.UserRegisterVo;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author liyd
 * @description
 * @date 2025/8/21 16:57
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("sms/sendCode")
    public R sendCode(@RequestParam("email") String email) {

        // TODO 接口防刷问题


        // 指定时间内只能发送一次验证码
        String existCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + email);

        if(existCode != null) {
            String[] codeInfoArr = existCode.split("_");
            String time  = codeInfoArr[1];
            if(System.currentTimeMillis() - Long.parseLong(time) <= 60000) {
                return R.error(ExceptionTypeEnum.VALID_SMS_CODE_EXCEPTION.getCode(),
                        ExceptionTypeEnum.VALID_SMS_CODE_EXCEPTION.getMessage());
            }
        }

        // 将时间信息整合在code中并存入redis
        String code = generateSixDigitCode();
        String time = System.currentTimeMillis() + "";
        String smsCode = code + "_" + time;

        stringRedisTemplate.opsForValue()
                .set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + email, smsCode, 60, TimeUnit.SECONDS);

        // 发送验证码
        thirdPartFeignService.sendCode(email, code);
        return R.ok();
    }


    @PostMapping("/register")
    public String register(@Validated UserRegisterVo userRegisterVo,
                           RedirectAttributes redirectAttributes,
                           BindingResult bindingResult
                           ) {
        if(bindingResult.hasErrors()) {

            Map<String, String> errors = bindingResult.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 校验验证码
        String existCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getEmail());
        if(existCode != null) {
            String[] codeInfoArr = existCode.split("_");
            String code  = codeInfoArr[0];
            if(code.equals(userRegisterVo.getCode())) {
                // 删除上次redis中验证码
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getEmail());

                // 将用户信息存入数据库
                MemberRegisterVo memberRegisterVo = new MemberRegisterVo();
                memberRegisterVo.setEmail(userRegisterVo.getEmail());
                memberRegisterVo.setUsername(userRegisterVo.getUsername());
                memberRegisterVo.setPassword(userRegisterVo.getPassword());

                R register = memberFeignService.register(memberRegisterVo);
                if(register.getCode() == 0) {
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData("msg", new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(@Validated UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession httpSession) {


        R login = memberFeignService.login(userLoginVo);
        if(login.getCode() != 0) {
            Map<String, String> errors = new HashMap<>();
            errors.put("", login.getData("msg", new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }else {
            MemberResponseVo data = login.getData(new TypeReference<MemberResponseVo>() {});
            httpSession.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        }
    }


    @GetMapping("/login.html")
    public String loginPage(HttpSession httpSession) {
        Object attribute = httpSession.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute == null) {
            return "redirect:http://auth.gulimall.com/login.html";
        }else {
            return "redirect:http://gulimall.com";
        }
    }

    private String generateSixDigitCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
}
